/*
 * IfNode.cpp
 *
 *  Created on: 28/dic/2010
 *      Author: computer
 */

#include "DerivationTree.h"
#include "IfInstruction.h"
#include "BlockInstruction.h"

IfNode::IfNode() : NodeTree_CRTP<IfNode>(), hasCondition(true) { }

IfNode::IfNode(const IfNode& copy) : NodeTree_CRTP<IfNode>(copy), hasCondition(copy.hasCondition), condition(copy.condition), listInstruction(copy.listInstruction) { }

void IfNode::setCondition(const AutoPointer<NodeTree>& _condition) {
	condition = _condition;
}

void IfNode::addInstruction(const AutoPointer<NodeTree>& instruction) {
	listInstruction.push_back(instruction);
}

void IfNode::setHasCondition(bool _condition) {
	hasCondition = _condition;
}

bool IfNode::execute(Pointer<LeonardVirtualMachine> LVM) {
	if (hasCondition) {
		TreeExpression::IfInstruction* ris = new TreeExpression::IfInstruction();
		std::list< AutoPointer<NodeTree> >::reverse_iterator j;
		for (j = listInstruction.rbegin(); j != listInstruction.rend(); ++j) {
			(*j)->execute(LVM);//Load the instruction
			ris->addInstruction(LVM->top());
			LVM->pop();
		}
		condition->execute(LVM);
		ris->setCondition(LVM->top());//set the condition
		LVM->pop();
		LVM->push(AutoPointer<TreeExpression::Expression>(ris));
	}
	else {
		TreeExpression::BlockInstruction* ris = new TreeExpression::BlockInstruction();
		std::list< AutoPointer<NodeTree> >::reverse_iterator j;
		for (j = listInstruction.rbegin(); j != listInstruction.rend(); ++j) {
			(*j)->execute(LVM);//Load the instruction
			ris->addInstruction(LVM->top());
			LVM->pop();
		}
		LVM->push(AutoPointer<TreeExpression::Expression>(ris));
	}
	return true;
}
